<?php
namespace App\Services;

use App\Helper\Utils\Util;
use App\Models\AdminModel;
use App\Models\LogInstorageModel;
use App\Models\LogOutstorageModel;
use App\Models\LogPackageModel;
use App\Models\ModuleModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\V3\Api\Services\DataFieldService;

class UsersService
{
    const SALT = 'storage';

    //获取审批人列表
    static public function approverList($parentId){
        return AdminModel::getApproverList($parentId);
    }

    //子账号列表
    static public function userList($parentId, $ata)
    {
        return AdminModel::userList($parentId, $ata);
    }

    //启禁用账号
    static public function transStatus($parentId, $data)
    {
        if(empty(SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        DB::beginTransaction();

        try {
            Redis::SET('user_id_'.$data['id'].'_disabled', 1);
            AdminModel::where('id', $data['id'])->lockForUpdate()->update(['is_active' => $data['status']]);
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    //重置子账号密码
    static public function resetPwd($parentId, $data)
    {
        if(empty(SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        AdminModel::where('id', $data['id'])->update([
            'password' => md5(md5('123456'.SELF::SALT)),
            'is_default_pwd' => 0
        ]);

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    //删除子账号信息
    static public function delUser($parentId, $data)
    {
        if(empty(SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        AdminModel::where('id', $data['id'])->update(['delete_flag' => 1]);

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    //新建子账号
    static public function addUser($parentId, $data)
    {
        $userInfo = AdminModel::where([
                                'username' => $data['username'],
                                'delete_flag' => 0
                            ])
                            ->first();
//
//        if(!empty($userInfo)) {
//            return ['code' => 1, 'msg' => '该账号已存在', 'data' => ''];
//        }

        $mainInfo = AdminModel::where('id', $parentId)->first();

        $data['parent_id'] = $parentId;
        $data['password'] = md5(md5('123456'.SELF::SALT));
        $data['newpwd'] = Util::randStr(6);
        $data['company_name'] = empty($mainInfo['company_name'])?'':$mainInfo['company_name'];
        $data['created_at'] = time();
        $data['is_active'] = $data['status'];
        unset($data['status']);

        $userId = AdminModel::insertGetId($data);

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    //修改子账号信息
    static public function editUserInfo($parentId, $data)
    {
        if(empty(SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        DB::beginTransaction();

        try {
            $data['is_active'] = $data['status'];
            unset($data['status']);

            AdminModel::where('id', $data['id'])->lockForUpdate()->update($data);
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    //设置子账号权限信息
    static public function setUser($parentId, $data)
    {
        if(empty(SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        DB::beginTransaction();

        try {
            AdminModel::where('id', $data['id'])->lockForUpdate()->update(['first_module'=>$data['first_module'],'second_module' =>$data['second_module']]);
            Redis::SET('user_id_'.$data['id'].'_reset', 1);

            //设置限制参数
            DataFieldService::setFieldPermission($data);

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    //获取子账号权限信息
    static public function getUserPermission($parentId, $data)
    {
        $parentModuleInfo = SELF::parentModuleInfo($parentId);

        if(empty($userInfo = SELF::common($parentId, $data))) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

        // $moduleInfo = ModuleService::roleModuleList();

        $arr = [];
        foreach($parentModuleInfo as $key => $value)
        {
            $arr[$key]['id'] = $value['id'];
            $arr[$key]['module_name'] = $value['module_name'];
            $arr[$key]['type'] = $value['type'];
            $arr[$key]['sort'] = $value['sort'];
            $arr[$key]['module_img'] = empty($value['module_img'])?'':$value['module_img'];

            if(in_array($value['id'], $userFirstModuleArr)) {
                $arr[$key]['is_enable'] = 1;
            }
            else {
                $arr[$key]['is_enable'] = 0;
            }

            foreach($value['second_module'] as $k => $v) {
                $arr[$key]['second_module'][$k]['module_img'] = empty($v['module_img'])?'':$v['module_img'];
                if(in_array($v['id'], $userSecondModuleArr)) {
                    $arr[$key]['second_module'][$k]['is_enable'] = 1;
                }
                else {
                    $arr[$key]['second_module'][$k]['is_enable'] = 0;
                }

                $arr[$key]['second_module'][$k]['id'] = $v['id'];
                $arr[$key]['second_module'][$k]['module_name'] = $v['module_name'];
                $arr[$key]['second_module'][$k]['type'] = $v['type'];
                $arr[$key]['second_module'][$k]['sort'] = $v['sort'];
                $arr[$key]['second_module'][$k]['upper_module_id'] = $v['upper_module_id'];
            }
        }

        return ['code' => 0, 'msg' => 'success', 'data' => $arr];
    }

    static private function parentModuleInfo($parentId)
    {
        $parentModuleInfo = AdminModel::select(
                                            'b.first_module',
                                            'b.second_module'
                                        )
                                        ->from('admin as a')
                                        ->leftJoin('role_setting as b', 'b.role_id', '=', 'a.admin_role')
                                        ->where('a.id', $parentId)->first();

        $parentFirstModule = array_filter(explode(',', $parentModuleInfo['first_module']), function($v) { return $v !== ''; });
        $parentSecondModule = array_filter(explode(',', $parentModuleInfo['second_module']), function($v) { return $v !== ''; });

        $moduleInfo = ModuleModel::select(
                                    'id',
                                    'module_name',
                                    'module_img',
                                    'sort',
                                    'type',
                                )
                                ->with('secondModule', function($query) use ($parentSecondModule) {
                                    $query->select(
                                                'id',
                                                'module_name',
                                                'module_img',
                                                'upper_module_id',
                                                'sort',
                                                'type',
                                            )
                                            ->where('delete_flag', 0)
                                            ->whereIn('id', $parentSecondModule)
                                            ->orderBy('sort', 'asc')
                                            ->orderBy('id', 'desc');
                                })
                                ->where('delete_flag', 0)
                                ->whereIn('id', $parentFirstModule)
                                ->orderBy('sort', 'asc')
                                ->orderBy('id', 'desc')
                                ->get()->toArray();

        return $moduleInfo;
    }

    static  private function common($parentId, $data)
    {
        $userInfo = AdminModel::where([
                                'parent_id' => $parentId,
                                'id' => $data['id'],
                                'delete_flag' => 0,
                            ])->first();

        return $userInfo;
    }

    //修改手机号
    static public function changeMobile($userId, $userType, $data)
    {
        if(!$userType) {
            //比对用户输入的code和短信发送的code是否一致
            if(!Redis::exists($data['mobile'].'_mobile_login')) {
                return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
            }
            else {
                if($data['code'] == Redis::get($data['mobile'].'_mobile_login')) {//验证码一致
                    $checkUserInfo = AdminModel::where('username', $data['mobile'])
                        ->where('parent_id', 0)
                        ->where('id', '!=', $userId)->first();

                    if(!empty($checkUserInfo)) {
                        return ['code' => 1, 'msg' => '手机号已存在，无法重复使用', 'data' => ''];
                    }
                    else {
                        AdminModel::where('id', $userId)->update([
                            'mobile' => $data['mobile'],
                            'username' => $data['mobile'],
                        ]);
                    }

                    Redis::del($data['mobile'].'_mobile_login');//销毁验证信息
                    return ['code' => 0, 'msg' => 'success', 'data' => ''];
                }
                else {
                    return ['code' => 1, 'msg' => '您输入的验证码有误，请重新输入', 'data' => ''];
                }
            }
        }
        else {
            Redis::del($data['mobile'].'_mobile_login');//销毁验证信息
            return ['code' => 1, 'msg' => '子账号无法完成此操作修改手机号', 'data' => ''];
        }
    }

    //修改手机号
    static public function modifyUserinfo($userId, $data)
    {
        AdminModel::where('id', $userId)->update($data);
        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    //修改用户密码
    static public function changePassword($userId, $data)
    {
        $userInfo = AdminModel::where('id', $userId)->first();

        if(md5(md5($data['old_pwd'].SELF::SALT)) != $userInfo['password']) {
            return ['code' => 1, 'msg' => '旧密码不正确', 'data' => ''];
        }

        AdminModel::where('id', $userId)->update([
            'password' => md5(md5($data['new_pwd'].SELF::SALT)),
            'is_default_pwd' => 1
        ]);

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    //个人中心
    static public function userCenter($userId, $mainId)
    {
        $data = AdminModel::select(
                                'a.id',
                                'username',
                                'nickname',
                                'mobile',
                                'parent_id',
                                'company_name',
                                'company_class',
                                'is_active',
                                'bind_id',
                                'invite_num',
                                'b.name',
                                'is_default_pwd',
                                'openid as is_bind_openid',
                                'wx_nickname'
                            )
                            ->from('admin as a')
                            ->leftJoin('company_class as b', 'a.company_class', '=', 'b.id')
                            ->where('a.id', $userId)->first();

        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        if($userId == $mainId) {
            $condition['main_id'] = ['EQ' => $mainId];
            unset($data['is_default_pwd']);
        }
        else {
            $condition['user_id'] = ['EQ' => $userId];
        }

        $mainInfo = AdminModel::where('id', $mainId)->first();

        $data['company_name'] = $mainInfo['company_name'];
        $data['parent_id'] = $mainId;
        $data['bind_id'] = $mainInfo['bind_id'];
        $data['invite_num'] = $mainInfo['invite_num'];
        $data['invite_info'] = SELF::inviteInfo($mainId);
        $data['is_bind_openid'] = empty($data['is_bind_openid'])?0:1;

        $data['today_in_storage'] = LogInstorageModel::getTodayInCount($condition, $startTime, $endTime);//今日入库总数
        $data['today_out_storage'] = LogOutstorageModel::getTodayOutCount($condition, $startTime, $endTime);//今日出库
        $data['today_package'] = LogPackageModel::getTodayPackageCount($condition, $startTime, $endTime);//今日套餐出库总数
        $data['today_trans_storage'] = LogOutstorageModel::getTodayAllocateCount($condition, $startTime, $endTime);//今日调拨数量

        return $data;
    }

    static public function inviteInfo($bindId)
    {
        $arr = [];
        if($bindId != 0) {
            $bindUserInfo = AdminModel::select('mobile')
                ->where('bind_id', $bindId)
                ->limit(3)
                ->orderBy('id', 'DESC')
                ->get();

            foreach($bindUserInfo as $value) {
                $arr[] = $value['mobile'];
            }
        }

        return $arr;
    }

    /**
     *
     * @param $mainId 主账号id
     * @param $data['pageSize'] 页面大小
     * @param $data['currentPage'] 当前页码
     * @return mixed
     * @author ソンブ
     * @created_at: 2022/2/17 11:20
     */
    static public function inviteList($mainId, $data)
    {
        $result = AdminModel::select('nickname', 'mobile')->where('bind_id', $mainId)
            ->orderBy('id', 'DESC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $result;
    }
}
